<template>
    <div class="padding20">
        <!--条件查询-->
        <el-form :model="queryParam" label-position="right" label-width="70px" size="small">
            <el-row :gutter="30" justify="start">
                <el-col :xs="12" :sm="7">
                    <el-form-item label-width="80px" label="查询日期:">
                        <el-date-picker
                                v-model="queryParam.time"
                                style="width: 100%"
                                type="month"
                                value-format="yyyy-MM-dd"
                                placeholder="选择月">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :xs="12" :sm="7">
                    <el-form-item label-width="80px" label="行业类别:">
                        <el-cascader
                                clearable
                                style="width: 100%"
                                v-model="queryParam.industryId"
                                :options="industryList"
                                :props="{value:'id', label: 'name'}"
                                :show-all-levels="false"/>
                    </el-form-item>
                </el-col>
                <el-col :xs="12" :sm="7">
                    <el-form-item label-width="80px" label="企业性质:">
                        <el-select clearable style="width: 100%" v-model="queryParam.unitType" multiple
                                   placeholder="企业性质">
                            <el-option
                                    v-for="item in unitTypeS"
                                    :key="item"
                                    :label="item"
                                    :value="item">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="12" :sm="7">
                    <el-form-item label-width="80px" label="企业规模:">
                        <el-select clearable style="width: 100%" v-model="queryParam.companyScale" placeholder="企业规模">
                            <el-option
                                    v-for="item in companyScaleS"
                                    :key="item"
                                    :label="item"
                                    :value="item">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="12" :sm="8">
                    <el-form-item label-width="10px">
                        <el-button size="small" @click="selectPage" type="primary">查询</el-button>
                        <el-button size="small" @click="clearParam">重置</el-button>
                        <a @click="showMoreSearch=!showMoreSearch"
                           style="margin-left: 8px ; font-size: 14px;color: #1890ff">
                            {{ showMoreSearch ? '收起' : '修改表头' }}
                            <i :class="showMoreSearch ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"/>
                        </a>
                    </el-form-item>
                </el-col>

                <!--展开/收起-->
                <div v-if="showMoreSearch">
                    <el-col :xs="24" :sm="24">
                        <el-form-item label-width="80px" label="岗位类别:">
                            <el-select @change="changeHandler($event,'jobType')" clearable multiple
                                       style="width: 100%" v-model="queryParam.jobType"
                                       placeholder="岗位类别">
                                <el-option
                                        v-for="item in jobTypeS"
                                        :key="item"
                                        :label="item"
                                        :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24">
                        <el-form-item label-width="80px" label="人员类型:">
                            <el-select @change="changeHandler($event,'peopleType')" clearable multiple
                                       style="width: 100%" v-model="queryParam.peopleType"
                                       placeholder="人员类型">
                                <el-option
                                        v-for="item in peopleTypeS"
                                        :key="item"
                                        :label="item"
                                        :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24">
                        <el-form-item label-width="80px" label="政治面貌:">
                            <el-select @change="changeHandler($event,'politicsFace')" clearable multiple
                                       style="width: 100%" v-model="queryParam.politicsFace"
                                       placeholder="政治面貌">
                                <el-option
                                        v-for="item in politicsFaceS"
                                        :key="item"
                                        :label="item"
                                        :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24">
                        <el-form-item label-width="80px" label="学历:">
                            <el-select @change="changeHandler($event,'learnLevel')" clearable multiple
                                       style="width: 100%" v-model="queryParam.learnLevel"
                                       placeholder="学历">
                                <el-option
                                        v-for="item in learnLevelS"
                                        :key="item"
                                        :label="item"
                                        :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24">
                        <el-form-item label-width="80px" label="性别:">
                            <el-select @change="changeHandler($event,'sex')" clearable multiple
                                       style="width: 100%" v-model="queryParam.sex" placeholder="性别">
                                <el-option
                                        v-for="item in sexS"
                                        :key="item"
                                        :label="item"
                                        :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24">
                        <el-form-item label-width="80px" label="年龄段:">
                            <el-select @change="changeHandler($event,'peopleAge')" clearable multiple
                                       style="width: 100%" v-model="queryParam.peopleAge"
                                       placeholder="年龄段">
                                <el-option
                                        v-for="item in peopleAgeS"
                                        :key="item"
                                        :label="item"
                                        :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </div>
            </el-row>
        </el-form>

        <!--操作按钮-->
        <div class="mi-container">
            <el-button size="mini" class="mi-item" type="primary" icon="el-icon-folder-opened" @click="exportExcel()">
                导出Excel
            </el-button>
        </div>

        <!--        岗位类别-->
        <!--        人员类型:-->
        <!--        政治面貌:-->
        <!--        学历:-->
        <!--        性别:-->
        <!--        年龄段-->
        <!--      -->
        <el-table  empty-text="当前条件下，暂无匹配数据"  :show-summary="true" :data="tableData" style="width: 100%"
                  :summary-method="getSummaries">
            <el-table-column align="center" label="日期" width="120">
                <template slot-scope="scope">
                    {{scope.row.dataMonth | nullFilter}}
                </template>
            </el-table-column>
            <el-table-column align="center" label="企业名" width="120">
                <template slot-scope="scope">
                    {{scope.row.name | nullFilter}}
                </template>
            </el-table-column>
            <el-table-column label="企业性质" width="200" align="center">
                <template slot-scope="scope">
                    <span v-if="!scope.row.unitType">暂无数据</span>
                    <el-tag v-else class="rit5" v-for="tag in split(scope.row.unitType)">
                        {{tag}}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="行业类别" align="center">
                <template slot-scope="scope">
                    {{ scope.row.industryName | nullFilter}}
                </template>
            </el-table-column>
            <el-table-column sortable
                             v-if="item"
                             v-for=" (item,index) in dynamicColumnName"
                             :prop="item"
                             :label="item"
                             align="center">
                <el-table-column sortable
                                 v-if="item2"
                                 v-for=" (item2,index2) in dynamicColumnLabel[index]"
                                 :prop="item2" :label="item2" align="center">
                    <template slot-scope="scope">
                        {{getColumnContent(scope.row,scope.$index,item,item2)}}
                    </template>
                </el-table-column>
            </el-table-column>
        </el-table>
        <!--分页插件-->
        <Pagination @pagination="selectPage"
                    v-show="pageParam.pages>0"
                    :total-data-num="pageParam.total"
                    :current-page="pageParam.current"
                    :page-size="pageParam.size"/>


        <el-table
                v-show="false"
                v-if="outTableIf"
                :data="outTableData"
                id="out-table"
                :show-summary="true"
                style="width: 100%"
                :summary-method="getSummaries">
            <el-table-column align="center" label="日期" width="120">
                <template slot-scope="scope">
                    {{scope.row.dataMonth | nullFilter}}
                </template>
            </el-table-column>
            <el-table-column align="center" label="企业名" width="120">
                <template slot-scope="scope">
                    {{scope.row.name | nullFilter}}
                </template>
            </el-table-column>
            <el-table-column label="企业性质" width="200" align="center">
                <template slot-scope="scope">
                    <span v-if="!scope.row.unitType">暂无数据</span>
                    <el-tag v-else class="rit5" v-for="tag in split(scope.row.unitType)">
                        {{tag}}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="行业类别" align="center">
                <template slot-scope="scope">
                    {{ scope.row.industryName | nullFilter}}
                </template>
            </el-table-column>
            <el-table-column sortable
                             v-if="item"
                             v-for=" (item,index) in dynamicColumnName"
                             :prop="item"
                             :label="item"
                             align="center">
                <el-table-column sortable
                                 v-if="item2"
                                 v-for=" (item2,index2) in dynamicColumnLabel[index]"
                                 :prop="item2" :label="item2" align="center">
                    <template slot-scope="scope">
                        {{getColumnContent(scope.row,scope.$index,item,item2)}}
                    </template>
                </el-table-column>
            </el-table-column>
        </el-table>
    </div>
</template>

<script lang="ts">
    import {Component} from 'vue-property-decorator'
    import {mixins} from "vue-class-component";
    import BaseVue from "@/core/mixin/BaseVue";
    import Kit from "@/core/mixin/Kit";
    import $http from "@/core/utils/http";
    import {API} from "@/core/api/API";
    import {getStorage} from "@/core/utils/storage";
    import {errorMsg, warningMsg} from "@/core/utils/message";
    import {copy, isBlank, tree} from "@/core/utils/Utils";
    import {subStr} from "@/core/filters";
    import XLSX from "xlsx";
    import FileSaver from "file-saver";
    import Pagination from "@/components/Pagination/Pagination.vue";
    import {closeLoading, showLoading} from "@/core/utils/loading";

    @Component({
        name: 'InWorkHumanTable',
        components: {Pagination},
    })
    export default class InWorkHumanTable extends mixins(BaseVue, Kit) {
        //查询条件
        queryParam: any = {time: getStorage("nowDate")}

        //合计
        getSummaries(param: any) {
            let {columns, data} = param;
            //console.log("data", data)
            let sums: any = [];
            columns.forEach((column: any, index: any) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }

                if (index === 1) {
                    sums[index] = '';
                    return;
                }

                if (index === 2) {
                    sums[index] = '';
                    return;
                }

                if (index === 3) {
                    sums[index] = '';
                    return;
                }


                // data = getStorage("m_b_data_b")

                const values = data.map((item: any) => {
                    ////console.log(item);
                    ////console.log(column.property);
                    let number = 0;
                    //找到这个属性对应的K
                    for (let k in item) {
                        if (item[k]) {
                            let parse;
                            try {
                                parse = JSON.parse(item[k]);
                            } catch (e) {
                                continue
                            }
                            number = parse[column.property]
                            if (number) {
                                ////console.log(" parse[column.property]--->" + number)
                                break;
                            }
                        }
                    }
                    return Number(number)
                });
                // ////console.log(values);

                if (!values.every((value: any) => isNaN(value))) {
                    sums[index] = values.reduce((prev: any, curr: any) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return prev + curr;
                        } else {
                            return prev;
                        }
                    }, 0);
                    // sums[index] += ' 人';
                }
            });
            // ////console.log(sums)
            return sums;
        }

        jobTypeS: any = getStorage("jobType");
        //性别
        sexS: any = ["男", "女"];
        //学历
        learnLevelS: any = getStorage("learnLevel");
        //政治面貌
        politicsFaceS: any = getStorage("politicsFace");
        //人员类型
        peopleTypeS: any = getStorage("peopleType");
        peopleAgeS: any = getStorage("peopleAge");
        companyScaleS: any = getStorage("companyScale");
        //企业性质
        unitTypeS: any = getStorage("companyType");
        //行业类别
        industryList: any = [];

        //返回该有的数据
        getColumnContent(row: any, index: any, type: any, child: any) {
            //console.log(type);
            let key = child;

            //
            if (row && type == '岗位类别' && row.jobType) {
                if (!row.jobType) return '暂无数据';
                return JSON.parse(row.jobType)[key];
            }
            //
            if (row && type == '人员类型' && row.peopleType) {
                if (!row.peopleType) return '暂无数据';
                return JSON.parse(row.peopleType)[key];
            }

            if (row && type == '政治面貌' && row.politicsFace) {
                if (!row.politicsFace) return '暂无数据';
                return JSON.parse(row.politicsFace)[key];
            }
            //
            if (row && type == '学历' && row.learnLevel) {
                if (!row.learnLevel) return '暂无数据';
                return JSON.parse(row.learnLevel)[key];
            }
            //
            if (row && type == '性别' && row.sex) {
                if (!row.sex) return '暂无数据';
                return JSON.parse(row.sex)[key];
            }
            //
            if (row && type == '年龄段' && row.peopleAge) {
                if (!row.peopleAge) return '暂无数据';
                return JSON.parse(row.peopleAge)[key];
            }
            return "暂无数据"
        }

        // 获取行业类型数据
        getIndustryTypeList() {
            $http.post(API.industryTypeList, {}).then((res: any) => {
                if (res.success) {
                    this.industryList = tree(res.data);
                } else {
                    errorMsg("行业类型数据获取失败");
                }
            });
        }

        dynamicColumnName: Array<any> = [];
        // dynamicColumnLabel: Array<any> = [];
        dynamicColumnProperty: Array<any> = [];
        dynamicColumnLabel: Array<any> = [];

        changeHandler(val: any, type: any) {
            //复选的长度
            let checkSize = val.length;
            // 岗位类别
            if (type == 'jobType') {
                this.queryParam.jobType = val;
                this.dynamicColumnName.splice(0, 1, checkSize == 0 ? null : "岗位类别");
                this.dynamicColumnLabel.splice(0, 1, checkSize == 0 ? null : val);
                this.dynamicColumnProperty.splice(0, 1, checkSize == 0 ? null : "jobType");
            }
            //人员类型
            if (type == 'peopleType') {
                this.queryParam.peopleType = val;
                this.dynamicColumnName.splice(1, 1, checkSize == 0 ? null : "人员类型");
                this.dynamicColumnLabel.splice(1, 1, checkSize == 0 ? null : val);
                this.dynamicColumnProperty.splice(1, 1, checkSize == 0 ? null : "peopleType");
            }
            // 政治面貌
            if (type == 'politicsFace') {
                this.queryParam.politicsFace = val;
                this.dynamicColumnName.splice(2, 1, checkSize == 0 ? null : "政治面貌");
                this.dynamicColumnLabel.splice(2, 1, checkSize == 0 ? null : val);
                this.dynamicColumnProperty.splice(2, 1, checkSize == 0 ? null : "politicsFace");
            }
            //学历
            if (type == 'learnLevel') {
                this.queryParam.learnLevel = val;
                this.dynamicColumnName.splice(3, 1, checkSize == 0 ? null : "学历");
                this.dynamicColumnLabel.splice(3, 1, checkSize == 0 ? null : val);
                this.dynamicColumnProperty.splice(3, 1, checkSize == 0 ? null : "learnLevel");
            }
            //性别
            if (type == 'sex') {
                this.queryParam.sex = val;
                this.dynamicColumnName.splice(4, 1, checkSize == 0 ? null : "性别");
                this.dynamicColumnLabel.splice(4, 1, checkSize == 0 ? null : val);
                this.dynamicColumnProperty.splice(4, 1, checkSize == 0 ? null : "sex");
            }
            //年龄段
            if (type == 'peopleAge') {
                this.queryParam.peopleAge = val;
                this.dynamicColumnName.splice(5, 1, checkSize == 0 ? null : "年龄段");
                this.dynamicColumnLabel.splice(5, 1, checkSize == 0 ? null : val);
                this.dynamicColumnProperty.splice(5, 1, checkSize == 0 ? null : "peopleAge");
            }
        }

        /**
         * 不能全部清空所以重写一下 clearParam（）
         * */
        clearParam() {
            this.queryParam.time = "";
            this.queryParam.industryId = "";
            this.queryParam.unitType = "";
            this.queryParam.companyScale = "";
        }


        initDynamicColumn() {
            this.dynamicColumnName = [];
            this.dynamicColumnLabel = [];

            this.dynamicColumnName.push("岗位类别")
            this.dynamicColumnName.push("人员类型")
            this.dynamicColumnName.push("政治面貌")
            this.dynamicColumnName.push("学历")
            this.dynamicColumnName.push("性别")
            this.dynamicColumnName.push("年龄段")

            this.queryParam.jobType = getStorage("jobType");
            this.queryParam.sex = ["男", "女"];
            this.queryParam.learnLevel = getStorage("learnLevel");
            this.queryParam.politicsFace = getStorage("politicsFace");
            this.queryParam.peopleType = getStorage("peopleType");
            this.queryParam.peopleAge = getStorage("peopleAge");

            this.dynamicColumnLabel.push(this.queryParam.jobType)
            this.dynamicColumnLabel.push(this.queryParam.peopleType)
            this.dynamicColumnLabel.push(this.queryParam.politicsFace)
            this.dynamicColumnLabel.push(this.queryParam.learnLevel)
            this.dynamicColumnLabel.push(this.queryParam.sex)
            this.dynamicColumnLabel.push(this.queryParam.peopleAge)

            // //////console.log(JSON.stringify(this.dynamicColumnName));
            // //////console.log(JSON.stringify(this.dynamicColumnProperty));
        }

        //初始化
        async mounted() {
            //初始化时间
            this.queryParam.time = getStorage("nowDate")

            this.initDynamicColumn();
            this.selectPage();
            this.getIndustryTypeList();
        }

        //查询分页
        selectPage(page: any = null) {
            if (isBlank(this.queryParam.time)) {
                warningMsg("请选择查询日期");
                return;
            }

            this.pageData(API.inWorkHumanStatisticsTablePage, page);
            // .then((res: any) => {
            //     setStorage("m_b_data_b", this.tableData)
            // })
        }

        //重新获取焦点
        activated() {
        }

        //失去焦点
        deactivated() {
        }


        /**
         * excel导出
         * @param outTableIf 使用时设置为true，使用后设置为false
         * @param outTableData 导出的数据，导出时需要给延时
         */
        outTableIf = false;
        outTableData = [];

        exportExcel() {
            if (isBlank(this.queryParam.time)) {
                warningMsg("请选择查询日期");
                return;
            }

            showLoading("正在导出excel...")
            this.outTableIf = true;
            let queryParam = copy(this.queryParam);
            queryParam.type = "all_export"
            $http.post(API.inWorkHumanStatisticsTablePage, queryParam)
                .then((res: any) => {
                    showLoading("正在导出excel...")
                    this.outTableData = res.data;
                    setTimeout(() => {
                        let fileName = this.queryParam.time ? '员工基本情况统计表' + subStr(this.queryParam.time, -3) + '.xlsx' : '员工基本情况统计表.xlsx';
                        // 转换成excel时，使用原始的格式，解决数字列自动转科学计数法问题
                        let xlsxParam = {raw: true};
                        // out-table关联导出的dom节点
                        let wb = XLSX.utils.table_to_book(document.querySelector('#out-table'), xlsxParam);
                        // 获取二进制字符串作为输出
                        let wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'});
                        try {
                            FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), fileName);
                        } catch (e) {
                            //console.log(e)
                        }
                        //还原状态
                        this.outTableIf = false;
                        this.outTableData = [];
                        closeLoading()
                    }, 2000)
                });
        }
    }

</script>

<style scoped type="scss">
</style>


